<?php
namespace App\Wen\Utils;

use App\Models\Bureau\WxBureau;
use App\Models\Bureau\WxBureauCollect;
use App\Models\Bureau\WxBureauComment;
use App\Models\Bureau\WxBureauGroup;
use App\Models\Bureau\WxClub;
use App\Models\Bureau\WxClubFollow;
use App\Models\Bureau\WxClubTeam;
use App\Models\User\WxUser;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class BureauUtils{

    public static function team_process(WxClubTeam &$clubTeam){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        $clubTeam->member_list = WxUser::whereIn('id', $clubTeam->members)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $clubTeam->members) . '"' . ")"))->get();

        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
            $info = self::get_join_info($__MINI_GLOBAL_CURRENT_USER_ID__, $clubTeam->bureau_id);
            if($info && _array_key($info, 'team_id', 0) == $clubTeam->id){
                $clubTeam->is_in_team = 1;
            }else{
                $clubTeam->is_in_team = 0;
            }
        }else{
            $clubTeam->is_in_team = 0;
        }
    }

    public static function group_process(WxBureauGroup &$wxBureauGroup){
        $member_total = 0;
        global $__MINI_GLOBAL_CURRENT_USER_ID__;

        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
            $info = self::get_join_info($__MINI_GLOBAL_CURRENT_USER_ID__, $wxBureauGroup->bureau_id);
            if($info && _array_key($info, 'group_id', 0) == $wxBureauGroup->id){
                $wxBureauGroup->is_in_group = 1;
            }else{
                $wxBureauGroup->is_in_group = 0;
            }
        }else{
            $wxBureauGroup->is_in_group = 0;
        }

        $wxBureauGroup->teams = WxClubTeam::where('group_id', $wxBureauGroup->id)->orderBy('id', 'asc')->get()->map(function ($team) use (&$member_total){
            self::team_process($team);
            $member_total += count($team->members);
            return $team;
        });
        $wxBureauGroup->member_total = $member_total;
        $wxBureauGroup->member_rest = $wxBureauGroup->total_people - $member_total;
    }

    public static function remove_seconds($str) {
        if (_empty_($str)) {
            return '';
        }
        $lastColonPos = strrpos($str, ':');
        if ($lastColonPos === false) {
            return $str;
        }
        return substr($str, 0, $lastColonPos);
    }

    public static function bureau_process(WxBureau &$wxBureau){
        global $__MINI_GLOBAL_CURRENT_USER_ID__,$__MINI_GLOBAL_SCENE__;
        $is_object_user_special = is_object_user_special($__MINI_GLOBAL_CURRENT_USER_ID__, $wxBureau->tenant_id, true);
        $now = Carbon::now();
        // is_in_bureau
        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
            $info = self::get_join_info($__MINI_GLOBAL_CURRENT_USER_ID__, $wxBureau->id);
            if($info && _array_key($info, 'bureau_id', 0) == $wxBureau->id){
                $wxBureau->is_in_bureau = 1;
            }else{
                $wxBureau->is_in_bureau = 0;
            }
        }else{
            $wxBureau->is_in_bureau = 0;
        }

        $wxBureau->user = UserUtils::get_cached_user($wxBureau->user_id, true);
        if($__MINI_GLOBAL_SCENE__ == 149){
            $wxBureau->service_time_tip = $wxBureau->service_date_start.' '. self::remove_seconds($wxBureau->service_time_start) . ' 至 '. str_replace($now->year.'-', '', $wxBureau->service_date_end) .' '.self::remove_seconds($wxBureau->service_time_end);
        }else{
            $wxBureau->service_time_tip = $wxBureau->service_date_start .' '. self::remove_seconds($wxBureau->service_time_start) . ' 至 '. str_replace($now->year.'-', '', $wxBureau->service_date_end) .' '.self::remove_seconds($wxBureau->service_time_end);
        }
        if($__MINI_GLOBAL_SCENE__ == 148){
            $wxBureau->club = WxClub::find($wxBureau->club_id);
        }else{
            $wxBureau->club = json_decode((string)(Cache::remember('club:info:'.$wxBureau->club_id, 7200, function () use (&$wxBureau){
                $the_club = WxClub::where('id', $wxBureau->club_id)->first(['id', 'name', 'avatar', 'intro', 'user_id', 'club_background_maps']);
                if($the_club){
                    return json_encode($the_club->toArray());
                }
                return json_encode(['name'=>'俱乐部已删除']);
            })), true);
        }


        if(_empty_($wxBureau->distance)){
            if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
                $wxBureau->distance = UserUtils::distance($__MINI_GLOBAL_CURRENT_USER_ID__, $wxBureau->longitude, $wxBureau->latitude);
            }
        }

        if($wxBureau->distance && $wxBureau->distance > 0){
            if($wxBureau->distance < 10){
                $wxBureau->distance = '<10m';
                $wxBureau->distance_name = $wxBureau->district;
            }else if($wxBureau->distance >= 1000 && $wxBureau->distance <= 200000){
                $wxBureau->distance = '<'. round($wxBureau->distance / 1000, 2).'km';
                $wxBureau->distance_name = $wxBureau->city;
            }else if($wxBureau->distance > 200000){
                $wxBureau->distance = round($wxBureau->distance / 1000, 2).'km';
                $wxBureau->distance_name = $wxBureau->province;
            }else{
                $wxBureau->distance = '<'.(int)$wxBureau->distance.'m';
                $wxBureau->distance_name = $wxBureau->district;
            }
        }else{
            $wxBureau->distance = '';
            $wxBureau->distance_name = $wxBureau->district;
        }
        if(_empty_($wxBureau->distance_name)){
            $wxBureau->distance_name = '';
        }

        if($wxBureau->image_urls){
            $wxBureau->pic = _array_key($wxBureau->image_urls[0], 'url', '') . '?imageMogr2/thumbnail/600x/format/webp/interlace/1';

            $wxBureau->pic_width = _array_key($wxBureau->image_urls[0], 'width', '');
            $wxBureau->pic_height = _array_key($wxBureau->image_urls[0], 'height', '');

            if($wxBureau->pic_width >= 0){
                $old_widht = $wxBureau->pic_width;
                $wxBureau->pic_width = 363;
                $wxBureau->pic_height = (int)( (363 * $wxBureau->pic_height) / $old_widht );
            }
        }

        if(_empty_($wxBureau->pic)){
            if($wxBureau->video_cover){
                $wxBureau->pic = $wxBureau->video_cover;
            }else{
                $wxBureau->pic = Settings::get('img_share_default', '');
            }
        }

        if(_empty_($wxBureau->pic_height)){
            $wxBureau->pic_height = 500;
        }

        $wxBureau->format_time = format_datetime($wxBureau->created_at);
        $wxBureau->groups = WxBureauGroup::where('bureau_id', $wxBureau->id)->orderBy('id', 'asc')->get()->map(function ($v){
            self::group_process($v);
            return $v;
        });

        $wxBureau->collect_count = (int)(Cache::remember('bureau:collect:count:'.$wxBureau->id, 3600,function () use (&$wxBureau){
            return WxBureauCollect::where('bureau_id', $wxBureau->id)->where('status', 1)->count();
        }));

        $allUserAvatars = [];
        $allMemberTotal = 0;
        $allMemberRest = 0;
        if($wxBureau->groups){
            foreach ($wxBureau->groups as $group) {
                $allMemberRest += $group->member_rest;
                if($group->teams){
                    foreach ($group->teams as $team) {
                        if($team->member_list){
                            foreach ($team->member_list as $member) {
                                $allUserAvatars[] = $member->user_avatar;
                                $allMemberTotal += 1;
                            }
                        }
                    }
                }
            }
        }

        // 限制为6个头像
        $wxBureau->member_total_all = $allMemberTotal;
        $wxBureau->member_rest_all = $allMemberRest;

        $wxBureau->avatars = Cache::remember('bureau:avatars:' . $wxBureau->id, 7200, function () use (&$wxBureau, &$allUserAvatars) {
            if ($wxBureau->member_total_all < $wxBureau->collect_count) {
                return WxUser::whereIn('id', function ($query) use (&$wxBureau) {
                    $query->select('user_id')->from('wx_bureau_collect')->where('bureau_id', $wxBureau->id)->where('status', 1)->orderBy('updated_at', 'desc');
                })->take(6)->pluck('user_avatar')->toArray();
            } else {
                return array_slice($allUserAvatars, 0, min(6, count($allUserAvatars)));
            }
        });

        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
            $wxBureau->is_collected = WxBureauCollect::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->where('bureau_id', $wxBureau->id)->where('status', 1)->exists();
        }else{
            $wxBureau->is_collected = false;
        }

        $wxBureau->comment_count = (int)(Cache::remember('bureau:comment:count:'.$wxBureau->id, 7200, function () use (&$wxBureau){
            return WxBureauComment::where('bureau_id', $wxBureau->id)->count();
        }));

        $wxBureau->activity_state = 0;
        if($wxBureau->status == 1){
            // 判断活动状态

            $serviceStartTime = Carbon::parse($wxBureau->service_date_start . ' ' . $wxBureau->service_time_start);
            $serviceEndTime = Carbon::parse($wxBureau->service_date_end . ' ' . $wxBureau->service_time_end);

            $signupStartTimes = [];
            $signupEndTimes = [];

            $canSignupGroups = [];
            $earliestSignupStartTime = Carbon::maxValue();
            $latestSignupEndTime = Carbon::minValue();

            foreach ($wxBureau->groups as $index => $group) {
                $signupStartTime = Carbon::parse($group->signup_start_time);
                $signupEndTime = Carbon::parse($group->signup_end_time);

                // 确保报名时间段在活动开始之前
                if ($signupEndTime->gt($serviceStartTime)) {
                    $signupEndTime = $serviceStartTime; // 将报名结束时间设置为活动开始时间
                }

                $signupStartTimes[] = $signupStartTime;
                $signupEndTimes[] = $signupEndTime;

                if ($signupStartTime->lte($now) && $signupEndTime->gte($now)) {
                    $canSignupGroups[] = $index + 1; // 组索引从1开始计数
                }

                if ($signupStartTime->lt($earliestSignupStartTime)) {
                    $earliestSignupStartTime = $signupStartTime;
                }
                if ($signupEndTime->gt($latestSignupEndTime)) {
                    $latestSignupEndTime = $signupEndTime;
                }
            }

            // 状态判断逻辑
            if ($now->lt($earliestSignupStartTime)) {
                $wxBureau->status_text = '报名未开始';
            } elseif (!empty($canSignupGroups)) {
                if($wxBureau->is_in_bureau){
                    $wxBureau->status_text = '已报名';
                }else{
                    if(count($canSignupGroups) == 1 && $wxBureau->groups->count() != 1){
                        $wxBureau->status_text = '可报名第' . implode(', 第', $canSignupGroups) . '组';
                    }else{
                        $wxBureau->status_text = '可报名';
                    }
                    $wxBureau->activity_state = 1;
                }

                // 检查报名条件
            } elseif ($now->gt($latestSignupEndTime) && $now->lt($serviceStartTime)) {
                $wxBureau->status_text = '等待活动开始';
            } elseif ($now->between($serviceStartTime, $serviceEndTime)) {
                $wxBureau->status_text = '活动进行中';
            } elseif ($now->gt($serviceEndTime)) {
                $wxBureau->status_text = '查看图集';
                $wxBureau->activity_state = 2;
            }
        }else if($wxBureau->status == 2){
            $wxBureau->status_text = '活动已下架';
        }else if($wxBureau->status == 3){
            $wxBureau->status_text = '管理员下架';
        }else{
            $wxBureau->status_text = '活动审核中';
        }


        // 生成note
        $note = '';
        if($wxBureau->groups && count($wxBureau->groups) == 1){
            $group = $wxBureau->groups->first();
            if (_empty_($group->signup_start_time)) {
                if ($group->signup_end_time) {
                    $note .= '报名截止时间：' . Carbon::parse($group->signup_end_time)->format('Y-m-d H:i') . '。'."\n";
                }
            } else {
                $note .= '报名时间：' . Carbon::parse($group->signup_start_time)->format('Y-m-d H:i') . ' 至 ' . Carbon::parse($group->signup_end_time)->format('Y-m-d H:i') . '。'."\n";
            }
            if ($group->signup_gender == 1) {
                $note .= '性别限制：仅限男性。'."\n";
            } elseif ($group->signup_gender == 2) {
                $note .= '性别限制：仅限女性。'."\n";
            } elseif ($group->signup_gender == 3) {
                $note .= '性别限制：男女比例1:1。'."\n";
            }
            if ($group->is_real_name == 1) {
                $note .= '实名认证：报名前需完成实名认证。'."\n";
            }
            if ($group->is_limit_one == 1) {
                $note .= '限购政策：每位用户限购一次。'."\n";
            }
        }else{
            foreach ($wxBureau->groups as $index => $group) {
                if (_empty_($group->signup_start_time)) {
                    if ($group->signup_end_time) {
                        $note .= ($group->name ?? ('第' . ($index+1) . '组')).'报名截止时间：' . Carbon::parse($group->signup_end_time)->format('Y-m-d H:i') . '。'."\n";
                    }
                } else {
                    $note .= ($group->name ?? ('第' . ($index+1) . '组')).'报名时间：' . Carbon::parse($group->signup_start_time)->format('Y-m-d H:i') . ' 至 ' . Carbon::parse($group->signup_end_time)->format('Y-m-d H:i') . '。'."\n";
                }
                if ($group->signup_gender == 1) {
                    $note .= ($group->name ?? ('第' . ($index+1) . '组')).'性别限制：仅限男性。'."\n";
                } elseif ($group->signup_gender == 2) {
                    $note .= ($group->name ?? ('第' . ($index+1) . '组')).'性别限制：仅限女性。'."\n";
                } elseif ($group->signup_gender == 3) {
                    $note .= ($group->name ?? ('第' . ($index+1) . '组')).'性别限制：男女比例1:1。'."\n";
                }
                if ($group->is_real_name == 1) {
                    $note .= ($group->name ?? ('第' . ($index+1) . '组')).'实名认证：报名前需完成实名认证。'."\n";
                }
                if ($group->is_limit_one == 1) {
                    $note .= ($group->name ?? ('第' . ($index+1) . '组')).'限购政策：每位用户限购一次。'."\n";
                }
            }
        }

        $refundData = [
            0 => '活动开始前随时可以退款',
            3 => '活动开始前3个小时可以退款',
            12 => '活动开始前12个小时可以退款',
            24 => '活动开始前24个小时可以退款',
            48 => '活动开始前48个小时可以退款',
            72 => '活动开始前3天可以退款',
            168 => '活动开始前7天可以退款',
            240 => '活动开始前10天可以退款',
            255 => '活动不支持无理由退款',
        ];
        if (array_key_exists($wxBureau->refund_policy, $refundData)) {
            $note .= '退款规则：'.$refundData[$wxBureau->refund_policy].'，活动费用为场地组织费，购买后因个人原因无法参加将不予退款。'."\n";
        }else{
            $note .= '退款规则：活动费用为场地组织费，购买后因个人原因无法参加将不予退款。'."\n";
        }
        $wxBureau->refund_policy_tip = _array_key($refundData, $wxBureau->refund_policy, '');
        $wxBureau->explain_list = [
            [
                'label' => '退款规则',
                'explain' => [_array_key($refundData, $wxBureau->refund_policy, '')]
            ],
            [
                'label' => '无条件退款规则',
                'explain' => ['因天气恶劣导致活动无法正常举行', '疫情原因导致活动无法举办']
            ],
//            [
//                'label' => '运动意外保障服务声明',
//                'explain' => ['动意外保障投保年龄范围为1岁（含）-70岁(含）', '不符合年龄范围会导致投保失败', '运动意外保障服务需要填写身份信息才会生效,因身份信息填写错误或未领取保障服务,均视为自动放弃该服务。']
//            ],
            [
                'label' => '免责声明',
                'explain' => ['因活动造成的意外损伤风险自担,平台及活动组织方无任何责任,报名成功视为自愿受本声明约束']
            ]
        ];

        if ($wxBureau->status == 1) {
            if ($wxBureau->activity_state == 1) {
                $note .= '活动状态：报名中。';
                if($__MINI_GLOBAL_CURRENT_USER_ID__ == $wxBureau->user_id || $is_object_user_special){
                    $wxBureau->action_sheets = ['自动回复', '下载用户信息', '重新发布', '编辑', '下架'];
                }
            } elseif ($wxBureau->activity_state == 2) {
                $note .= '活动状态：活动已结束，可查看活动图集。';
                if($__MINI_GLOBAL_CURRENT_USER_ID__ == $wxBureau->user_id || $is_object_user_special){
                    $wxBureau->action_sheets = ['下载用户信息', '重新发布'];
                }
            } else {
                $note .= '活动状态：'.$wxBureau->status_text;
                if($__MINI_GLOBAL_CURRENT_USER_ID__ == $wxBureau->user_id || $is_object_user_special){
                    $wxBureau->action_sheets = ['扫码验票', '自动回复', '下载用户信息', '重新发布', '编辑', '下架'];
                }
            }
        }else if($wxBureau->status == 2){
            $note .= '活动状态：活动已下架。';
            if($__MINI_GLOBAL_CURRENT_USER_ID__ == $wxBureau->user_id || $is_object_user_special){
                $wxBureau->action_sheets = ['重新发布'];
            }
        }else if($wxBureau->status == 3){
            $note .= '活动状态：活动被管理员下架。';
            if($__MINI_GLOBAL_CURRENT_USER_ID__ == $wxBureau->user_id || $is_object_user_special){
                $wxBureau->action_sheets = ['重新发布'];
            }
        } else {
            $note .= '活动状态：活动审核中。';
            if($__MINI_GLOBAL_CURRENT_USER_ID__ == $wxBureau->user_id || $is_object_user_special){
                $wxBureau->action_sheets = ['自动回复', '编辑'];
            }
        }
        $wxBureau->note = $note;
    }

    public static function get_join_info($user_id, $bureau_id){
        return json_decode(Cache::remember('get_join_info:'.$bureau_id.':'.$user_id, 3600, function () use ($bureau_id, $user_id){
            $team = WxClubTeam::where('bureau_id', $bureau_id)->where('members', 'like', "%'".$user_id."'%")->first();
            if($team){
                return json_encode(['bureau_id' => $team->bureau_id, 'group_id' => $team->group_id, 'team_id'=>$team->id]);
            }
            return json_encode([]);
        }), true);
    }


    public static function club_bg_color_update($club_id, $force_update_default = false){
        if(!$force_update_default){
            if(_empty_($club_id)){
                return '';
            }
        }
        $color_arr = [
            [81, 76, 74],
            [63, 47, 45],
            [52, 55, 39],
            [78, 90, 97],
            [75, 71, 65],
            [89, 77, 86],
            [75, 80, 85],
            [113, 93, 94],
            [132, 84, 0],
            [18, 14, 17],
            [30, 38, 72],
            [62, 56, 95],
            [26, 39, 74],
            [74, 69, 74],
            [49, 36, 75],
            [35, 67, 86],
            [114, 112, 90]
        ];

        $is_update_site = false;
        if(!$force_update_default){
            $bg = WxClub::where('id', $club_id)->value('club_background_maps');
        }else{
            $club_id = 0;
            $bg = '';
        }

        if(_empty_($bg)){
            if(!$force_update_default){
                $default_background_color = get_site_meta('club_background_color', 's');
                if(!_empty_($default_background_color)){
                    if($club_id > 0){
                        update_object_meta(2, $club_id, 'club_background_color', $default_background_color);
                    }
                    return $default_background_color;
                }
            }

            $bg = Settings::get('club_background_maps', '');
            if(_empty_($bg)){
                if($club_id > 0) {
                    update_object_meta(2, $club_id, 'club_background_color', implode(',', [63, 47, 45]));
                }
                return implode(',', [14, 14, 14]);
            }
            $is_update_site = true;
        }
        try {
            if(strpos($bg, 'img.mini.chongyeapp.com') !== false){
                $bg = str_replace('img.mini.chongyeapp.com', 'img.mini.minisns.cn', $bg);
            }
            // 设置图片路径
            $imagePath = file_get_contents($bg);
            $img = Image::make($imagePath);
            $mainColor = $img->limitColors(1)->pickColor(0, 0, 'array');
            $res_color = ImageUtils::find_closed_color($color_arr, $mainColor);
            if($res_color){
                $res_color = implode(',', $res_color);
                if($club_id > 0) {
                    update_object_meta(2, $club_id, 'club_background_color', $res_color);
                }
                if($is_update_site){
                    update_site_meta('club_background_color', $res_color);
                }
                return $res_color;
            }
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            return implode(',', [14, 14, 14]);
        }
    }


    public static function club_procee(&$club){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        $club->user = UserUtils::get_cached_user($club->user_id);

        $club->collect_count = WxBureauCollect::where('club_id', $club->id)->where('status', 1)->count();
        $club->part_count = WxClubTeam::where('club_id', $club->id)->sum('members_num');
        $club->follow_count = (WxClubFollow::where('club_id', $club->id)->where('status', 1)->count()) ?: 0;
        $club->is_follow = WxClubFollow::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->where('club_id', $club->id)->where('status', 1)->exists();
        $club->avatar_frame_url = '';
        $club->longtaps = [];

        $club->club_background_color = '14, 14, 14';
//                $club->club_background_color = get_object_meta(2, $club->id, 'club_background_color');
//                if(_empty_($club->club_background_color)){
//                    $club->club_background_color = BureauUtils::club_bg_color_update($club->id);
//                    if(_empty_($club->club_background_color)){
//                        $club->club_background_color = '14, 14, 14';
//                    }
//                }

        if($club->status === 0){
            $club->status_tip = '俱乐部正在审核中';
        }else if($club->status === 1){
            $club->status_tip = '正常状态';
        }else if($club->status === 2){
            $ban_until = get_object_meta(2, $club->id, 'ban_until', 's');
            if(time() > $ban_until){
                // 解除封号
                if(BureauUtils::unlock_club($club, 2)){
                    $club->status_tip = '正常状态';
                }
            }
            if($ban_until && _empty_($club->status_tip)){
                $club->status_tip = '该俱乐部被封号至'. \Carbon\Carbon::createFromTimestamp($ban_until)->toDateTimeString();
            }
        }else if($club->status === 3){
            $mute_until = get_object_meta(2, $club->id, 'mute_until', 's');
            if(time() > $mute_until){
                // 解除禁言
                if(BureauUtils::unlock_club($club, 3)){
                    $club->status_tip = '正常状态';
                }
            }
            if($mute_until && _empty_($club->status_tip)){
                $club->status_tip = '该俱乐部被禁言至'.Carbon::createFromTimestamp($mute_until)->toDateTimeString();
            }
        }

        $managers = [
            [
                'id' => $club->user['id'],
                'user_name' => $club->user['user_name'],
                'user_avatar' => $club->user['user_avatar'],
                'user_introduce' => $club->user['user_introduce']
            ]
        ];

        $assistants = _empty_default_(json_decode(_empty_default_($club->assistants, '[]'), true), []);
        if($assistants){
            foreach ($assistants as $assistant){
                $assistant_user = UserUtils::get_cached_user($assistant);
                if($assistant_user){
                    $managers[] = [
                        'id' => $assistant_user['id'],
                        'user_name' => $assistant_user['user_name'],
                        'user_avatar' => $assistant_user['user_avatar'],
                        'user_introduce' => $assistant_user['user_introduce']
                    ];
                }
            }
        }

        $club->managers = $managers;

        $club->append(['ip_address']);
    }


    /**
     * @param $user
     * @param $type 3:禁言 2：封号
     * @param $timestamp
     * @param string $black_reason
     * @return bool
     */
    public static function lock_club($club, $type, $timestamp, $black_reason = ''){
        if($club){
            if($type == 2){
                DB::beginTransaction();
                try {
                    // todo:
                    WxClub::where('id', $club['id'])->update( [ 'status' => 2, 'black_reason' => $black_reason ] );
                    update_object_meta(2, $club['id'], 'ban_until', $timestamp, 's');
                    DB::commit();
                    return true;
                } catch (\Exception $e) {
                    DB::rollBack();
                    _logger_(__file__, __line__, $e->getMessage());
                    return false;
                }
            }else if($type == 3){
                DB::beginTransaction();
                try {
                    // todo:
                    WxClub::where('id', $club['id'])->update( [ 'status' => 3, 'black_reason' => $black_reason ] );
                    update_object_meta(2, $club['id'], 'mute_until', $timestamp, 's');
                    DB::commit();
                    return true;
                } catch (\Exception $e) {
                    DB::rollBack();
                    _logger_(__file__, __line__, $e->getMessage());
                    return false;
                }
            }
        }
        return false;
    }

    public static function unlock_club($club, $type){
        if($club){
            if($type == 2){
                if($club['status'] === 2){
                    $ban_until = get_object_meta(2, $club['id'], 'ban_until', 's');
                    // 解除封号
                    DB::beginTransaction();
                    try {
                        // todo:
                        WxClub::where('id', $club['id'])->update( [ 'status' => 1 ] );
                        update_object_meta(2, $club['id'], 'ban_until', null, 's');
                        DB::commit();
                        return true;
                    } catch (\Exception $e) {
                        DB::rollBack();
                        _logger_(__file__, __line__, $e->getMessage());
                        return false;
                    }
                }
            }else if($type == 3){
                if($club['status'] === 3){
                    $mute_until = get_user_meta($club['id'], 'mute_until', 's');
                    // 解除禁言
                    DB::beginTransaction();
                    try {
                        // todo:
                        WxClub::where('id', $club['id'])->update( [ 'status' => 1 ] );
                        update_object_meta(2, $club['id'], 'mute_until', null, 's');

                        DB::commit();
                        return true;
                    } catch (\Exception $e) {
                        DB::rollBack();
                        _logger_(__file__, __line__, $e->getMessage());
                        return false;
                    }
                }
            }
            return false;
        }else{
            return false;
        }
    }


}
